﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Solidi
{
	/// <summary>
	/// Thread safe
	/// </summary>
	sealed class AutoDependency : IDependency, IDependencyLifestyle
	{
		private IDependencyKey _key;
		private Func<IDependencyContainer, IDependency, object> _factory;

		public AutoDependency(IDependencyKey key)
		{
			_key = key;
		}

		public IDependencyKey Key { get { return _key; } }

		public Func<IDependencyContainer, IDependency, object> Factory
		{
			get
			{
				if (_factory == null)
				{
					_factory = (c, d) =>
					{
						object instance;

						c.Composer.TryCompose(c, _key.Type, d.Parameters, out instance);

						return instance;
					};
				}

				return _factory;
			}
		}

		public IDependencyLifestyle Lifestyle { get { return this; } }

		public object AcquireToken(object graphId)
		{
			return graphId;
		}

		public bool DiscardToken(object token)
		{
			return true;
		}

		public Action<object> Disposer { get { return instance => { }; } }

		public IEnumerable<IDependencyParameter> Parameters { get { yield break; } }
	}
}
